package com.lank.gateway.filter;

import com.nimbusds.jose.JWSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.function.Consumer;


/**
 * 将登录用户的JWT转化成用户信息的全局过滤器
 *
 * @author 郑海宾
 * @date 2020/6/17
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(AuthGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("Authorization");
        String keyId = headers.getFirst("key-id");

        Consumer<HttpHeaders> httpHeaders = httpHeader -> {
            httpHeader.set("accountId", getAccount(token));
        };

        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders).build();

        exchange = exchange.mutate().request(serverHttpRequest).build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private String getAccount(String token) {
        try {
            if (StringUtils.hasText(token)) {
                String realToken = token.replace("Bearer ", "");
                JWSObject jwsObject = JWSObject.parse(realToken);
                Map<String, Object> jsonObject = jwsObject.getPayload().toJSONObject();
                Object sub = jsonObject.get("sub");
                return sub.toString();
            }
        } catch (Exception e) {
            log.warn("解析用户信息失败！");
        }
        return "";
    }
}